<template>
  <div class="vue-uploader">
    <div class="file-list">
      <section :key="index" class="file-item draggable-item" v-for="(file, index) of files">
        <img :src="file.src" alt ondragstart="return false;" />
        <!-- <p class="file-name">{{file.name}}</p> -->
        <span @click="remove(index)" class="file-remove">+</span>
      </section>
      <section class="file-item" v-if="status == 'ready'">
        <div @click="add" class="add">
          <span>+</span>
        </div>
      </section>
    </div>

    <section class="upload-func" v-if="files.length != 0">
      <div class="progress-bar">
        <section :width="(percent * 100) + '%'" v-if="uploading">{{(percent * 100) + '%'}}</section>
      </div>
      <div class="operation-box">
        <button @click="submit" v-if="status == 'ready'">上传</button>
        <button @click="finished" v-if="status == 'finished'">完成</button>
      </div>
    </section>
    <input @change="fileChanged" accept="image/*" multiple="multiple" ref="file" type="file" />
  </div>
</template>
<script>
  export default {
    props: {
      src: {
        type: String,
        required: true
      },
      autoUpload: {
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        status: 'ready',
        files: [],
        point: {},
        uploading: false,
        percent: 0
      }
    },
    methods: {
      add() {
        this.$refs.file.click()
      },
      submit() {
        if (this.files.length === 0) {
          console.warn('no file!')
          return
        }
        const formData = new FormData()
        this.files.forEach(item => {
          formData.append(item.name, item.file)
        })
        const xhr = new XMLHttpRequest()
        xhr.upload.addEventListener('progress', this.uploadProgress, false)
        xhr.open('POST', this.src, true)
        this.uploading = true
        xhr.send(formData)
        xhr.onload = () => {
          this.uploading = false
          if (xhr.status === 200 || xhr.status === 304) {
            this.status = 'finished'
            console.log('upload success!')
          } else {
            console.log(`error：error code ${xhr.status}`)
          }
        }
      },
      submitOne() {
        const file = this.$refs.file.files[0]
        console.log(file)

        const formData = new FormData()
        formData.append(file, file)
        const xhr = new XMLHttpRequest()
        xhr.upload.addEventListener('progress', this.uploadProgress, false)
        xhr.open('POST', this.src, true)
        this.uploading = true
        xhr.send(formData)
        xhr.onload = () => {
          this.uploading = false
          if (xhr.status === 200 || xhr.status === 304) {
            this.status = 'finished'
            console.log('upload success!')
          } else {
            console.log(`error：error code ${xhr.status}`)
          }
        }
      },
      finished() {
        this.files = []
        this.status = 'ready'
      },
      remove(index) {
        this.files.splice(index, 1)
      },
      fileChanged() {
        if (this.autoUpload) {
          this.submitOne()
          return
        }
        const list = this.$refs.file.files
        for (let i = 0; i < list.length; i++) {
          if (!this.isContain(list[i])) {
            const item = {
              name: list[i].name,
              size: list[i].size,
              file: list[i]
            }
            this.html5Reader(list[i], item)
            console.log(2)
            this.files.push(item)
            // 这里单张上传
          }
        }
        this.$refs.file.value = ''
      },
      // 将图片文件转成BASE64格式
      html5Reader(file, item) {
        const reader = new FileReader()
        reader.onload = e => {
          this.$set(item, 'src', e.target.result)
        }
        reader.readAsDataURL(file)
      },
      isContain(file) {
        return this.files.find(
          item => item.name === file.name && item.size === file.size
        )
      },
      uploadProgress(evt) {
        const component = this
        if (evt.lengthComputable) {
          const percentComplete = Math.round((evt.loaded * 100) / evt.total)
          component.percent = percentComplete / 100
        } else {
          console.warn('upload progress unable to compute')
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
  .vue-uploader {
    border: 1px solid #e5e5e5;
  }
  .vue-uploader .file-list {
    padding: 1px 0px;
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
  }
  .vue-uploader .file-list:after {
    content: '';
    display: block;
    clear: both;
    visibility: hidden;
    line-height: 0;
    height: 0;
    font-size: 0;
  }
  .vue-uploader .file-list .file-item {
    position: relative;
    text-align: center;
    width: 33.3%;
    height: rem(200);
    margin: rem(20) 0;
  }
  .vue-uploader .file-list .file-item img {
    width: rem(200);
    height: rem(200);
    border: 1px solid #ececec;
  }
  .vue-uploader .file-list .file-item .file-remove {
    position: absolute;
    right: 0;
    /* display: none; */
    top: -rem(10);
    width: 20px;
    height: 20px;
    color: white;
    cursor: pointer;
    line-height: 17px;
    text-align: center;
    border-radius: 100%;
    transform: rotate(45deg);
    background: rgba(255, 0, 0, 0.8);
  }
  .vue-uploader .file-list .file-item:hover .file-remove {
    /* display: inline; */
  }
  .vue-uploader .file-list .file-item .file-name {
    margin: 0;
    height: 40px;
    word-break: break-all;
    font-size: 14px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
  .vue-uploader .add {
    width: rem(200);
    height: rem(200);
    margin: 0 auto;
    // margin-left: 10px;
    text-align: center;
    line-height: rem(200);
    border: 1px dashed #ececec;
    font-size: 30px;
    cursor: pointer;
  }
  .vue-uploader .upload-func {
    display: flex;
    padding: 10px;
    margin: 0px;
    background: #f8f8f8;
    border-top: 1px solid #ececec;
  }
  .vue-uploader .upload-func .progress-bar {
    flex-grow: 1;
  }
  .vue-uploader .upload-func .progress-bar section {
    margin-top: 5px;
    background: #00b4aa;
    border-radius: 3px;
    text-align: center;
    color: #fff;
    font-size: 12px;
    transition: all 0.5s ease;
  }
  .vue-uploader .upload-func .operation-box {
    flex-grow: 0;
    padding-left: 10px;
  }
  .vue-uploader .upload-func .operation-box button {
    padding: 4px 12px;
    color: #fff;
    background: #007acc;
    border: none;
    border-radius: 2px;
    cursor: pointer;
  }
  .vue-uploader > input[type='file'] {
    display: none;
  }
</style>
